package vn.isolar.io;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlSerializer;

import vn.isolar.main.SvntestActivity;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;

public class TomCatClient {
	String addr = "http://isolar.vn:9406/ServerControl/";
	HttpClient httpclient;
	HttpPost httppost;
	HttpEntity resEntity;
	Context context;

	public TomCatClient(Context context) {
		this.context = context;
		httpclient = new DefaultHttpClient();
		httppost = new HttpPost(addr);
	}

	public String execute(String xml_file, String audio_file)
			throws ClientProtocolException, IOException {
		httpclient.getParams().setParameter(
				CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

		
		// TODO Auto-generated method stub
		if (audio_file == "" || audio_file == null) {
			File x_file = new File(xml_file);
			MultipartEntity mpEntity = new MultipartEntity();
			FileBody fileBody = new FileBody(x_file);

			mpEntity.addPart("xml", fileBody);
			httppost.setEntity(mpEntity);
			System.out
					.println("executing request " + httppost.getRequestLine());
			HttpResponse response;
			response = httpclient.execute(httppost);
			return handerResponse(response);
		} else {
			httpclient.getParams().setParameter(
					CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

			File x_file = new File(xml_file);
			File a_file = new File(audio_file);

			MultipartEntity mpEntity = new MultipartEntity();
			FileBody fileBody = new FileBody(x_file, "application/xml");
			FileBody fileBody2 = new FileBody(a_file);

			mpEntity.addPart("xml", fileBody);
			mpEntity.addPart("file", fileBody2);

			httppost.setEntity(mpEntity);

			System.out
					.println("executing request " + httppost.getRequestLine());
			HttpResponse response;
			response = httpclient.execute(httppost);
			return handerResponse(response);
		}
	}

	/*----------------------------------------------------------
	 * Hander respondse here, return result or return "" if error
	 */
	public String handerResponse(HttpResponse response) {
		String result = "test";
		resEntity = response.getEntity();

		System.out.println(response.getStatusLine());
		if (resEntity != null) {
			try {
				result = EntityUtils.toString(resEntity);
				if (resEntity != null) {
					resEntity.consumeContent();
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		// dropConnection();
		return result;
	}

	private void dropConnection() {
		httpclient.getConnectionManager().shutdown();
	}

	/*
	 * Function query for TTS and return link of file audio Created date: 13/8
	 * by: Do Quoc Truong
	 */
	public String synthesise(String text) {
		// TODO Auto-generated method stub
		String linkAudio = "http://isolar.vn:9406/ServerControl";
		// request server here
		String xml_file;
		try {
			xml_file = createXML("TTS", text);
			linkAudio += execute(xml_file, "");
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// end request server
		return linkAudio;
	}

	public void execute(String text) {
		String link = null;
		try {
			link = synthesise(text);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		MediaPlayer mp = new MediaPlayer();
		mp = MediaPlayer.create(context, Uri.parse(link));

		if (mp != null) {
			mp.start();
		}

	}

	/*
	 * Function Create File XML To Request
	 * 
	 * @ Du Dan
	 */
	public String createXML(String type, String request)
			throws IllegalArgumentException, IllegalStateException, IOException {
		if (request == "") {
			request = "asr";
		}
		// Create XML File to Request TTS
		XmlSerializer xmlSerializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();

		xmlSerializer.setOutput(writer);
		// start DOCUMENT
		xmlSerializer.startDocument("UTF-8", true);
		// open tag: <company>
		xmlSerializer.startTag("", "company");
		// open tag: <staff>
		xmlSerializer.startTag("", "staff");
		// open tag: <type>
		xmlSerializer.startTag("", "type");
		xmlSerializer.text(type);
		// end tag: <type>
		xmlSerializer.endTag("", "type");
		// open tag: <request>
		xmlSerializer.startTag("", "request");
		xmlSerializer.text(request);
		// end tag: <request>
		xmlSerializer.endTag("", "request");
		// end tag: <staff>
		xmlSerializer.endTag("", "staff");
		// end tag: <company>
		xmlSerializer.endTag("", "company");

		// end DOCUMENT
		xmlSerializer.endDocument();

		String xmlFile = writer.toString();
		File lfile = null;
		// try to write the content

		File lroot = Environment.getExternalStorageDirectory();

		lfile = new File(lroot, type + ".xml");

		FileWriter lfilewriter = new FileWriter(lfile);
		BufferedWriter lout = new BufferedWriter(lfilewriter);
		lout.write(xmlFile);
		lout.close();
		return lfile.getPath();
	}

}
